package cn.sinjet.communication.bluetooth;

import java.util.Arrays;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import cn.sinjet.model.carsystem.CarModel;
import cn.sinjet.model.mcuupgrade.McuUpgradeModel;

public class BTWorkingHandler extends Handler{
		public static final int BT_MSG_SEND_UPGRADE_FILE_DELAY_TIME = (1000/14);
		public static final int BT_MSG_SEND_DELAY_TIME = 80;
	   public static final int  MSG_SEND_BT = 1;
	   public static final int  MSG_INIT_BT = 2;
	   public static final int  MSG_CONNECT_BT = 3;
	   public static final int  MSG_DISCONNECT_BT = 4;
	   public static final int  MSG_KEEP_CONNECTED = 5;
	   public static final String KEY_BT_MSG = "KEY_BT_MSG";
	   BluetoothModel btModel = null;
	   public BTWorkingHandler(Looper looper,BluetoothModel btModel){
		   super(looper);
		   this.btModel = btModel;
	   }
	   public int msgBuffCount = 0;
	   
	   @Override
	public void handleMessage(Message msg) {
		// TODO Auto-generated method stub
		//super.handleMessage(msg);
	     switch(msg.what){
	     case MSG_INIT_BT:{
	    	 btModel.initBTInThread();
	     }
	     break;
	     case MSG_CONNECT_BT:
	    	 btModel.connectBTInThread();
	    	 break;
	     case MSG_DISCONNECT_BT:
	    	 btModel.diconnectBTInThread();
	    	 break;
	     case MSG_SEND_BT:{
	    	    Bundle bundle = msg.getData();
	    	    byte[] message = bundle.getByteArray(KEY_BT_MSG);
	    	    btModel.sendMessageInThread(message);
	    	    try{
	    	    	if (McuUpgradeModel.getInstance().isThreadFrameSendRun) {
		    	    	Thread.sleep(BT_MSG_SEND_UPGRADE_FILE_DELAY_TIME);
	    	    	}
	    	    	else {
		    	    	Thread.sleep(BT_MSG_SEND_DELAY_TIME);
	    	    	}
	    	    }catch(Exception e){
	    	    	e.printStackTrace();
	    	    }
	    	    if (1 == CarModel.getInstance().devModule.getMCUUpgradeMethod()) {
	    	    	if (Arrays.equals(message, McuUpgradeModel.getInstance().lastMsg)) {
	    	    		msgBuffCount = 0;
	    	    	}
		    	}
	    	    if (msgBuffCount > 0)
	    	    {
	    	    	msgBuffCount--;
	    	    }
	    	 }
	    	 break;
	     case MSG_KEEP_CONNECTED:
	    	 btModel.tryToKeepConnectedInThread();
	    	 break;
	     }
	}
	   
}
